package com.sunxiansheng.exception;

import com.sunxiansheng.exception.response.RespBeanEnum;
import com.sunxiansheng.exception.response.Result;
import com.sunxiansheng.exception.strategys.ExceptionStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * Description: 全局异常处理器
 *
 * @Author sun
 * @Create 2024/5/6 15:16
 * @Version 1.0
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    // 将所有的策略都注入进来
    private final List<ExceptionStrategy> strategies;

    @Autowired // 可以省略，只有一个构造器，会默认使用这个构造器注入
    public GlobalExceptionHandler(List<ExceptionStrategy> strategies) {
        this.strategies = strategies;
    }

    /**
     * 根据不同的异常类型，决定不同的策略
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e) {
        log.error("Exception caught: ", e);
        for (ExceptionStrategy strategy : strategies) {
            if (strategy.supports(e)) {
                return strategy.handleException(e);
            }
        }
        return Result.fail(RespBeanEnum.ERROR);
    }

}